var omeShopExGoodsEditor = new Class({
    Implements:[Options],
    options: {
        periodical: false,
        delay: 500,
        postvar:'finderItems',
        varname:'items',
        width:500,
        height:400
    },
    initialize: function(el, options){
        this.el = $(el);
        this.setOptions(options);
        this.cat_id = $('gEditor-GCat-input').getValue();
        this.type_id = $('gEditor-GType-input').getValue();
        this.goods_id = $('gEditor-GId-input').getValue();
        this.initEditorBody.call(this);
    },
    initEditorBody:function(){
        var _this=this;
        var gcatSelect=$('gEditor-GCat-input');
        var gtypeSelect=$('gEditor-GType-input');
        var gbrandSelect=$('dom_el_202ad50');
        var gbrandButton=$('search_brand_btn');
        
        var showTypeAndBrand = function(){
        	_this.type_id=gtypeSelect.getValue();
			new Request({
				url : '/ome/admin_goods_editor/getTypeProps/',
				method : 'post',
				data : 'type_id=' + _this.type_id,
				onSuccess : function(responseText, responseXML){
					$('type_details').setHTML(responseText);
				}
			}).send();
			
			new Request({
				url : '/ome/admin_goods_editor/getTypeBrands/',
				method : 'post',
				data : 'type_id=' + _this.type_id,
				onSuccess : function(responseText, responseXML){
					var tpl = '<option value="{brand_id}">{brand_name}</option>';
					var html = tpl.replace(/{brand_id}/i, '').replace(/{brand_name}/i, '请选择所属品牌');

					var brands = JSON.decode(responseText);
					if(brands.length != 0){
						for(var k in brands){
							html += tpl.replace(/{brand_id}/i, k).replace(/{brand_name}/i, brands[k]);
						}
					}
					
					var selectedBrandValue = $($('dom_el_202ad50').options[$('dom_el_202ad50').selectedIndex]).get('value');
					$('dom_el_202ad50').setHTML(html);
					var target = $('dom_el_202ad50').getElement('option[value^='+selectedBrandValue+']');
					if(target != null){
						$('dom_el_202ad50').getElement('option[value^='+selectedBrandValue+']').set('selected',true);
					}else{
						$($('dom_el_202ad50').options[0]).set('selected',true);
					}
				}
			}).send();
        };
        
        
        
        gcatSelect.addEvent('change',function(e){
            var selectedOption=$(this.options[this.selectedIndex]);
            var typeid=selectedOption.get('type_id') || '';
            var goods_name = $('id_gname').get('value');
            
            //if(typeid!=gtypeSelect.getValue() && goods_name!=''){
            if(typeid != gtypeSelect.getValue()){
            	if(confirm('\t重设分类将会丢失当前所输入的相关数据，确定吗？')||this.getValue()<0){
            		gtypeSelect.getElement('option[value='+typeid+']').set('selected',true);
            		showTypeAndBrand();
            		//_this.updateEditorBody.call(_this);
				}
            }
            _this.cat_id = this.getValue();
        });
        gtypeSelect.addEvent('click',function(){
        	this.store('tempvalue',this.getValue());        	
        });
        gtypeSelect.addEvent('change',function(e){
            var tmpTypeValue = this.retrieve('tempvalue');
            var goods_name = $('id_gname').get('value');
            //if (goods_name!=''){
				//if(this.getValue() && confirm('重设类型将会丢失当前所输入的相关数据，确定吗？')){
				if(confirm('重设类型将会丢失当前所输入的相关数据，确定吗？')){
					showTypeAndBrand();
					//_this.updateEditorBody.call(_this);
				}else{
					this.getElement('option[value='+tmpTypeValue+']').set('selected',true);
	            }
           //}
        });
        gbrandButton.addEvent('click', function(){
        	var sbn = $('search_brand_name').get('value').trim();
        	if(sbn == ''){
        		alert('请输入品牌名称');
        		return;
        	}
        	
        	var isFound = false;
        	for(var i=0;i<gbrandSelect.options.length;i++){
        		var brandName = gbrandSelect.options[i].text;
        		var brandValue = gbrandSelect.options[i].value;
        		if(brandName == sbn){
        			gbrandSelect.getElement('option[value^='+brandValue+']').set('selected',true);
        			isFound = true;
        			break;
        		}
        	}
        	
        	if(!isFound){
        		alert('没找到品牌：'+sbn);
        	}	
        });
        
    },
    updateEditorBody:function(options){
    	if($('productNode')&&$('productNode').retrieve('specOBJ')){
    		$('productNode').appendChild($('productNode').retrieve('specOBJ').toHideInput($('productNode').getElement('tr')));		
		}
    	
    	var parma = {
    			update:'gEditor-Body',
    			data:$('gEditor').toQueryString() + '&pic_bar='+encodeURIComponent( $E('#action-pic-bar .pic-area').get('html') ),
    			method:'post',
    			onComplete:function(callHtml){
    				alert(goodsEditFrame);
			   		goodsEditFrame();
    			}
    	};
       W.page('/ome/admin_goods_editor/update/',parma);
    },
    mprice:function(e){
        for(var dom=e.parentNode; dom.tagName!='TR';dom=dom.parentNode){;}
        var info = {};
        $ES('input',dom).each(function(el){
            if(el.name == 'price[]')
                info['price']=el.value;
            else if(el.name == 'goods[product][0][price]')
                info['price']=el.value;
            else if(el.getAttribute('level'))
                info['level['+el.getAttribute('level')+']']=el.value;
        });
        window.fbox = new Dialog('index.php?app=ome&ctl=admin_goods_editor&act=set_mprice',{title:'编辑会员价', ajaxoptions:{data:info,method:'post'},modal:true});
        window.fbox.onSelect = goodsEditor.setMprice.bind({base:goodsEditor,'el':dom});
    },
    setMprice:function(arr){
        var parr={};
        arr.each(function(p){
            parr[p.name] = p.value;
        });
        $ES('input',this.el).each(function(d){
            var level = d.getAttribute('level');
            if(level && parr[level]!=undefined){
                d.value = parr[level];
            }
        });
    },
    spec:{
        addCol:function(s,typeid){
            this.dialog = new Dialog('/ome/admin_goods_editor/set_spec/?_form='+(s?s:'goods-spec')+'&p[0]='+typeid,{ajaxoptions:{data:$('goods-spec').toQueryString()+($('nospec_body')?'&'+$('nospec_body').toQueryString():''),method:'post'},title:'规格'});
        },
        addRow:function(){
            this.dialog = new Dialog('index.php?app=ome&ctl=admin_goods_editor/spec&act=addRow',{ajaxoptions:{data:$('goods-spec'),method:'post'}});
        }
    },
    adj:{
        addGrp:function(s){
            this.dialog = new Dialog('index.php?app=ome&ctl=admin_goods_editor&act=addGrp&_form='+(s?s:'goods-adj'));
        }
    },
    pic:{
        del:function(ident,obj){
            if(confirm('确认删除本图片吗?')){
                obj = $(obj);
                var pic_box=obj.getParent('.gpic-box');
                try{
	                if(ident){
	                    new Request({
	                    	url:'/ome/admin_goods/removePic/',
	                    	data:{ ident : ident },
	                    	onSuccess:function(){
		                    	pic_box.remove();
		                       
		                    	if($E('#all-pics .gpic-box .current'))return;
		                    	if($$('#all-pics .gpic-box').length&&$$('#all-pics .gpic-box').length>0){
		                    		$('x-main-pic').empty().set('html','<div class="notice" style="margin:0 auto">请重新选择默认商品图片.</div>');
		                    	}else{
		                    		$('x-main-pic').empty().set('html','<div class="notice" style="margin:0 auto">您还未上传商品图片.</div>');
		                    	}
	                    	}
	                    }).send();
	                }
	            }catch(e){
                   pic_box.remove();
                }                
            }
        },
        setDefault:function(id,imgstr){
            if(isNaN(id))return;
			if($('x-main-pic').retrieve('cururl')==imgstr){
				return;
			}
            $('x-main-pic').store('cururl','loading');
            var lastdft = this.getDefault();
            if(lastdft){
               lastdft=$E('#all-pics img[sn=_img_'+lastdft+']');
                if(lastdft)lastdft.getParent('span').removeClass('current');
            }
            if($E('#x-main-pic input[name=image_default]')){
               $E('#x-main-pic input[name=image_default]').set('value',id);
            }else{
               $('x-main-pic').empty();
               new Element('input',{type:'hidden',name:'image_default'}).set('value',id).inject('x-main-pic');
            }
            if(_temimg=$('x-main-pic').getElements('img')){
               if(_temimg.length){
            	   for(var i=0; i<_temimg.length; i++){
            		   var t = _temimg[i];
            		   t.remove();
            	   }
               }
            }
            
            $('x-main-pic').addClass('x-main-pic-loading');
           
            new Asset.image(imgstr,{
                onload:function($1){
            		var _img=$($1.zoomImg(290,220));    
            		_img.inject($('x-main-pic'));  
                    _img.setStyle('margin-top',Math.abs((220-_img.height.toInt())/2));      
                    $('x-main-pic').removeClass('x-main-pic-loading');
                	$('x-main-pic').store('cururl',imgstr);
                },
                onerror:function(){
                        $('x-main-pic').removeClass('x-main-pic-loading');
                        $('x-main-pic').store('cururl','');
                }
            }); 
            if($E('#all-pics img[sn=_img_'+id+']'))
            $E('#all-pics img[sn=_img_'+id+']').getParent('span').addClass('current');
        },
        getDefault:function(){
            var o = $E('#x-main-pic input[name=image_default]');
            if(o){
                return o.value;
            }else{return false};
        },
        viewSource:function(act){
           return new Dialog(act,{title:'查看图片信息',singlon:false,'width':650,'height':300});
        }
    },
    rateGoods:{
        add:function(){
            window.fbox = new Dialog('index.php?ctl=goods/product&act=select',{modal:true,ajaxoptions:{data:{onfinish:'goodsEditor.rateGoods.insert(data)'},method:'post'}});
        },
        del:function(){
        },
        insert:function(data){
            $ES('div.rate-goods').each(function(e){
                data['has['+e.getAttribute('goods_id')+']'] = 1;
            });
            new Ajax('index.php?ctl=goods/product&act=ratelist',{data:data,onComplete:function(s){$('x-rate-goods').innerHTML+=s}}).request();
        }
    }
});
